<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>Smart Portal</h1>
        <p>欢迎用户登录系统</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            autocomplete="off"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              size="large"
              :prefix-icon="Key"
              maxlength="4"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image" @click="refreshCaptcha" v-html="captchaSvg"></div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-tips">
        <p>点击验证码图片可刷新</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { getCaptcha } from '@/api/auth'
import { User, Lock, Key } from '@element-plus/icons-vue'

interface LoginForm {
  username: string
  password: string
  captcha: string
}

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const loginFormRef = ref<FormInstance | null>(null)
const loading = ref(false)
const captchaSvg = ref('')
const captchaId = ref('')

const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  captcha: ''
})

const loginRules: FormRules<LoginForm> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, message: '密码长度不能少于3位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位', trigger: 'blur' }
  ]
}

// 获取验证码
const refreshCaptcha = async (): Promise<void> => {
  try {
    const res = await getCaptcha()
    if (res.code === 200) {
      captchaId.value = res.data.id
      captchaSvg.value = res.data.svg
      // 清空验证码输入
      loginForm.captcha = ''
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

const handleLogin = async (): Promise<void> => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!captchaId.value) {
        ElMessage.warning('请先获取验证码')
        await refreshCaptcha()
        return
      }
      
      loading.value = true
      const success = await authStore.login({
        username: loginForm.username,
        password: loginForm.password,
        captchaId: captchaId.value,
        captcha: loginForm.captcha
      })
      loading.value = false
      
      if (success) {
        const redirect = route.query.redirect
        router.push(typeof redirect === 'string' ? redirect : '/')
      } else {
        // 登录失败后刷新验证码
        await refreshCaptcha()
      }
    }
  })
}

// 组件挂载时获取验证码
onMounted((): void => {
  refreshCaptcha()
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 420px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  padding: 40px;
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
  
  h1 {
    font-size: 32px;
    font-weight: 700;
    color: #333;
    margin: 0 0 10px 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
  
  p {
    color: #666;
    font-size: 14px;
    margin: 0;
  }
}

.login-form {
  :deep(.el-form-item) {
    margin-bottom: 24px;
  }
  
  :deep(.el-input__wrapper) {
    border-radius: 8px;
  }
}

.login-button {
  width: 100%;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  
  &:hover {
    opacity: 0.9;
  }
}

.captcha-container {
  display: flex;
  gap: 12px;
  width: 100%;
  
  .el-input {
    flex: 1;
  }
  
  .captcha-image {
    width: 120px;
    height: 40px;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      background-color: #ecf5ff;
    }
    
    :deep(svg) {
      width: 100%;
      height: 100%;
    }
  }
}

.login-tips {
  margin-top: 20px;
  text-align: center;
  
  p {
    color: #999;
    font-size: 12px;
    margin: 0;
  }
}
</style>

